'use strict';

const jwt = require('jsonwebtoken');

const Controller = require('../../core/common');

class WeappController extends Controller {

  async login() {
    const { ctx, app } = this;
    const loginService = app.weapp.LoginService.create(ctx.request, ctx.response);
    await loginService.login().then(data => {
      ctx.body = data;
    });
  }

  async user() {
    const { ctx, app } = this;
    const loginService = app.weapp.LoginService.create(ctx.request, ctx.response);
    await loginService.check().then(data => {
      ctx.body = {
        code: 0,
        message: 'ok',
        data: {
          userInfo: data.userInfo,
        },
      };
    });
  }

  // 微信授权
  async show() {
    const { app, ctx } = this;

    const { id } = ctx.params;
    if (!id) ctx.throw(401, 'code为空');

    const result = await ctx.curl(
      `https://api.weixin.qq.com/sns/jscode2session?appid=${app.config.wechat.AppID}&secret=${app.config.wechat.AppSecret}&js_code=${id}&grant_type=authorization_code`, {
        dataType: 'json'
      }
    );

    const openId = result.data.openid;

    console.log(openId, 'openId');

    if (openId) {
      // let usersInfo = await ctx.service.v1.access.weapp.wxHasRegister(openId); // 判断是否新用户
      // // 新用户注册
      // if (usersInfo === false) {
      //   usersInfo = await ctx.service.v1.access.weapp.wxRegister({
      //     openId,
      //     userInfo: {},
      //   });
      // }

      // this.setToken({ id: usersInfo.get('id') });

      // this.success(usersInfo);

      this.success({ openId })

      // setDataValue

    } else {
      ctx.throw(500, '获取 openId失败');
    }

    ctx.status = result.status;
  }

  async create() {
    const { app } = this;

    this.token = { id: 1 }

    this.success({ token: this.ctx.state.token });
  }

  set token({ id }) {
    let token = ''

    try {
      token = jwt.sign({ id }, this.app.config.jwt.secret, { expiresIn: '7d' });
    } catch (e) {
      ctx.throw(500, '获取 Token失败');
    }

    this.ctx.state.token = token
    this.ctx.set('Authorization', `Bearer ${token}`);
  }

  async update() {
    this.success('update')
  }

}

module.exports = WeappController;